/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in Pw
*@des: message
*@name: message.h
*@author: zhognsx
*@time: 2015-11-16
*********************************************************/
#include <iostream>
#include <string>
#include "message.h"


//提供对自定义msg的封装
//message 缓冲区 
//不能竞争操作
message::message()
{
	data_ = NULL;
	wlen = 0;
	mlen = 0;
	//
	reset();
}

message::~message()
{
	if (data_){
		delete[] data_;
		//pool->ordered_free(data_, mlen);
		data_ = NULL;
	}
}

const char* message::data() const
{
	return (char*)data_;
}

char* message::data()
{
	return (char*)data_;
}

char* message::header()
{
	return (char*)data_;
}

char* message::body()
{
	return (char*)(data_ + sizeof(msgHead));
}

void message::reset()
{
	if (data_ == NULL){
		malloc(MIN_LEN);
	}
	memset(data_, 0, MIN_LEN);
	wlen = 0;
	mlen = MIN_LEN;
}
//分配空间
void message::malloc(int size)
{
	if (data_){
		//pool->ordered_free(data_, mlen);
		delete[] data_;
		data_ = NULL;
	}
	data_ = new uint8_t[size];
	//(uint8_t*)pool->ordered_malloc(size);
	BOOST_ASSERT(data_ != NULL);
	wlen = 0;
	mlen = size;
}

//自定义扩展内存
void message::relloc(uint32_t size)
{
	int nlen = wlen + size;
	uint8_t* ndata_ = new uint8_t[nlen];
		//(uint8_t*)pool->ordered_malloc(nlen);
	BOOST_ASSERT(ndata_ != NULL);
	//new char[nlen];
	memset(ndata_, 0, nlen);
	//copy
	memcpy(ndata_, data_, wlen);
	//pool->ordered_free(data_, mlen);
	delete[] data_;
	data_ = ndata_;
	mlen = nlen;
}


//封装数据
void message::encode_data(const char* data, int length)
{
	if (data == NULL){
		return;
	}
	//数据检查
	if (data_ == NULL){
		malloc(length);
	}
	//数据区小了。不能重复利用
	if (length > mlen){
		malloc(length);
	}
	//
	memset(data_, 0, length);
	memcpy(data_, data, length);
	wlen = length;
}

int message::length()
{//
	return (wlen > 0) ? wlen : 0;
}

int message::header_len()
{
	return sizeof(msgHead);
}

//在调用时 数据区已写入sizeof(msgHead) 大小的数据
int message::body_len()
{
	msgHead* head = (struct msgHead *)data_;
	return (head->dwSize - sizeof(msgHead));
}

void message::add_wlen(int size)
{
	wlen += size;
}

int message::get_mlen()
{
	return mlen;
}
